package org.easy.excel.support;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import org.easy.excel.support.config.ExcelConfig;
import org.easy.excel.support.config.entity.ExportStreamSupport;

import java.io.OutputStream;
import java.util.Collection;
import java.util.List;

/**
 * EasyExcel 导出顶级接口
 *
 * @author 李坤
 * @date 2022/4/24 23:31
 */
public interface ExcelExportService {

    /**
     * Excel 文件数据导出
     *
     * @param outputStream 输出流对象
     * @param dataList     数据集合
     * @param excelConfig  相关配置
     */
    default void export(OutputStream outputStream, ExcelConfig excelConfig) {
        // Excel导出类构造器
        final ExcelWriterBuilder writerBuilder = EasyExcel.write(outputStream).head(excelConfig.getExcelExportHeaderList());

        for (WriteHandler writeHandler : excelConfig.getWriteHandlerList()) {
            writerBuilder.registerWriteHandler(writeHandler);
        }
        writerBuilder.sheet(excelConfig.getSheetName()).doWrite(excelConfig.getExcelExportDataList());
    }

    /**
     * 获取{@link ExportStreamSupport}对象实例
     *
     * @param outputStream  输出流
     * @param excelHeads    Excel标题
     * @param writeHandlers Excel处理拦截器
     * @param sheetName     SheetName
     *
     * @return {@link ExportStreamSupport}对象实例
     */
    default ExportStreamSupport getExportStreamSupport(OutputStream outputStream, List<List<String>> excelHeads,
                                                       Collection<WriteHandler> writeHandlers, String sheetName) {
        // Excel导出类构造器
        final ExcelWriterSheetBuilder writerSheetBuilder = EasyExcel.writerSheet(sheetName).head(excelHeads);
        // 添加Excel拦截器
        writeHandlers.forEach(writerSheetBuilder::registerWriteHandler);

        return ExportStreamSupport.getInstance(outputStream, writerSheetBuilder);
    }

}
